﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp.UI;
using CustomsDocumentOA.Project.CusDocument.Dto;
using CustomsDocumentOA.Project.Users;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace CustomsDocumentOA.Project.CusDocument
{
    public class CDOA_WorkOrderAppservice : AsyncCrudAppService<CDOA_WorkOrder, WorkOrderDto, Guid, PagedResultRequestDto, UpdateWorkOrderDto, UpdateWorkOrderDto>, ICDOA_WorkOrderAppservice
    {
        private readonly IObjectMapper _objectMapper;
        public readonly IUserAppService _userAppService;
        public CDOA_WorkOrderAppservice(IRepository<CDOA_WorkOrder, Guid> repository, IObjectMapper objectMapper, IUserAppService userAppService) : base(repository)
        {
            _objectMapper = objectMapper;
            _userAppService = userAppService;
        }
        #region 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="CurrentPage"></param>
        /// <param name="PageSizes"></param>
        /// <param name="state">工单状态,0进行中;1作废;2已完成</param>
        /// <param name="businessManager">业务员</param>
        /// <param name="assignment">指派人</param>
        /// <param name="customName">客户名</param>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public async Task<PagedResultDto<WorkOrderDto>> GetList(int CurrentPage, int PageSizes, int state = 3, string businessManager = "", string assignment = "", string customName = "", long userId = 0)
        {
            PagedResultDto<WorkOrderDto> resultDto = new PagedResultDto<WorkOrderDto>();
            List<CDOA_WorkOrder> lists = new List<CDOA_WorkOrder>();
            Expression<Func<CDOA_WorkOrder, bool>> expr = o => o.Id != null;
            if (state != 1)
            {
                if (state == 0)
                {
                    expr = expr.ExpressionAnd(o => o.Status == state);
                }
                if (state == 2)
                {
                    expr = expr.ExpressionAnd(o => o.Status == state);
                }
                else
                {

                    expr = expr.ExpressionAnd(o => o.Status == 0 || o.Status == 2);
                }

            }
            else
            {
                expr = expr.ExpressionAnd(o => o.Status == state);
            }
            if (userId > 0)
            {
                var obj = await _userAppService.GetUserName(userId);
                if (obj != null)
                {
                    expr = expr.ExpressionAnd(o => o.BusinessManager == obj.Name);
                }
            }
            if (!string.IsNullOrEmpty(businessManager))
            {
                expr = expr.ExpressionAnd(o => o.BusinessManager.Contains(businessManager));
            }
            if (!string.IsNullOrEmpty(assignment))
            {
                expr = expr.ExpressionAnd(o => o.Assignment.Contains(assignment));
            }
            if (!string.IsNullOrEmpty(customName))
            {
                expr = expr.ExpressionAnd(o => customName.Contains(o.CustomName));
            }
            lists = await Repository.GetAll().Where(expr).ToListAsync();
            lists = lists.OrderByDescending(o => o.CreationTime).ToList();
            var dtos = lists.Skip((CurrentPage - 1) * PageSizes).Take(PageSizes).ToList();
            resultDto.Items = _objectMapper.Map<List<WorkOrderDto>>(dtos);
            resultDto.TotalCount = lists.Count;
            return resultDto;
        }
        #endregion

        #region 获取时间戳
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        #endregion

        #region 创建工单
        /// <summary>
        /// 创建工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<WorkOrderDto> CreateWorkOrder(CreateWorkOrder input)
        {
            string st = GenerateTimeStamp();
            UpdateWorkOrderDto workOrder = new UpdateWorkOrderDto();
            workOrder.CustomName = input.CustomName;
            workOrder.WorkOrderNo = "A" + st;
            workOrder.EndTime = input.EndTime;
            workOrder.IsCancel = false;
            workOrder.Title = input.Title;
            workOrder.Status = 0;
            workOrder.dateTime = input.dateTime;
            if (!string.IsNullOrEmpty(input.Memo))
            {
                workOrder.Memo = input.Memo;
            }
            if (!string.IsNullOrEmpty(input.Contact))
            {
                workOrder.Contact = input.Contact;
            }
            var result = await base.CreateAsync(workOrder);
            return result;
        }
        #endregion

        #region 工单派工
        /// <summary>
        /// 工单派工
        /// </summary>
        /// <param name="id"></param>
        /// <param name="assignment">指派人</param>
        /// <param name="businessManager">业务员</param>
        /// <param name="expectedTime">预计完成时间</param>
        /// <returns></returns>
        public async Task<WorkOrderDto> AssignmentWork(Guid id, string assignment, string businessManager, DateTime expectedTime)
        {
            var obj = await Repository.FirstOrDefaultAsync(o => o.Id == id);
            obj.Assignment = assignment;
            obj.BusinessManager = businessManager;
            obj.ExpectedTime = expectedTime;
            var result = await Repository.InsertOrUpdateAsync(obj);
            return _objectMapper.Map<WorkOrderDto>(result);
        }
        #endregion

        #region 工单重新派单
        /// <summary>
        /// 工单重新派单
        /// </summary>
        /// <param name="reCreate"></param>
        /// <returns></returns>
        public async Task<WorkOrderDto> ReCreateWorkOrder(ReCreateWorkOrder reCreate)
        {
            var obj = await Repository.FirstOrDefaultAsync(o => o.Id == reCreate.WorkId);
            if (obj == null)
                throw new UserFriendlyException("工单不存在");
            obj.IsCancel = true;
            obj.Status = 1;
            await Repository.InsertOrUpdateAsync(obj);
            UpdateWorkOrderDto input = new UpdateWorkOrderDto();
            if (!string.IsNullOrEmpty(obj.Memo))
            {
                input.Memo = obj.Memo;
            }
            if (!string.IsNullOrEmpty(obj.Contact))
            {
                input.Contact = obj.Contact;
            }
            input.CustomName = obj.CustomName;
            input.Title = obj.Title;
            input.Assignment = reCreate.Assignment;
            input.BusinessManager = reCreate.BusinessManager;
            input.EndTime = reCreate.EndTime;
            input.ExpectedTime = reCreate.ExpectedTime;
            input.UserId = reCreate.UserId;
            input.WorkOrderNo = "A" + GenerateTimeStamp();
            input.CustomName = obj.CustomName;
            input.IsCancel = false;
            input.Status = 0;
            input.dateTime = reCreate.dateTime;
            var order = await base.CreateAsync(input);
            return order;
        }
        #endregion

        #region 更改工单状态
        /// <summary>
        /// 更改工单状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status">工单状态,0进行中;1作废;2已完成</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> UpdateStatus(Guid id, int status)
        {
            var obj = await Repository.FirstOrDefaultAsync(o => o.Id == id);
            if (obj != null)
            {
                if (status == 1)
                {
                    obj.Status = status;
                    obj.IsCancel = true;
                }
                else
                {
                    obj.Status = status;
                }
                return "成功";
            }
            else
            {
                return "失败,请联系管理员";
            }
        }
        #endregion

        #region 今日新增工单
        /// <summary>
        /// 今日新增工单
        /// </summary>
        /// <param name="CurrentPage"></param>
        /// <param name="PageSizes"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<WorkOrderDto>> GetWorkerCount(int CurrentPage, int PageSizes)
        {
            PagedResultDto<WorkOrderDto> resultDto = new PagedResultDto<WorkOrderDto>();
            List<CDOA_WorkOrder> lists = new List<CDOA_WorkOrder>();
            lists = await Repository.GetAll().Where(it => it.CreationTime.Date == DateTime.Now.Date).ToListAsync();
            lists = lists.OrderByDescending(it => it.CreationTime).ToList();
            var dtos = lists.Skip((CurrentPage - 1) * PageSizes).Take(PageSizes).ToList();
            resultDto.Items = _objectMapper.Map<List<WorkOrderDto>>(dtos);
            resultDto.TotalCount = lists.Count;
            return resultDto;
        }
        #endregion

        #region 批量删除
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteList(string id)
        {
            string[] obj = id.Split(",");
            for (int i = 0; i < obj.Length; i++)
            {
                await Repository.DeleteAsync(Guid.Parse(obj[i]));
            }
        }
        #endregion
    }
}
